package com.example.travelsn.homepage;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.travelsn.R;
import com.example.travelsn.db.DBManager;
import com.example.travelsn.db.Seller;
import com.example.travelsn.db.User;
import com.example.travelsn.service.UserService;
import com.example.travelsn.util.MD5Util;

import java.util.logging.Logger;

public class RegisteOrLogin extends AppCompatActivity implements View.OnClickListener {
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    String userType;
    int type;
    //文本框
    private EditText name;
    private EditText npassword;

    //按钮

    //数据库操作
    DBManager dbManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_and_login);
        initEvent();
        initSpinner();
    }
    @Override
    public void onClick(View v) {
        String username = name.getText().toString();
        String password = MD5Util.md5(npassword.getText().toString());
        System.out.println("用户名： "+username);
        System.out.println("密码： "+password);
        switch (v.getId()) {
            //注册事件
            case R.id.b_register:
                if(username.length()>=3 && password.length()>=6){
                    System.out.println("正在注册");
                    register(userType,username,password);
                    //UserService.signIn(username,password);
                    Toast.makeText(RegisteOrLogin.this,"重新登陆吧",Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(RegisteOrLogin.this,"用户名长度至少为3",Toast.LENGTH_SHORT).show();
                break;
            //登录事件
            case R.id.b_login:
                System.out.println("正在登录");
                login(userType,username,password);
                break;
            default:
                break;
        }
    }
    //点击屏幕 关闭输入弹出框
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        return super.onTouchEvent(event);
    }
        public void initEvent(){
        Button bRegister = (Button) findViewById(R.id.b_register);
        Button bLogin = (Button)findViewById(R.id.b_login);
        name = (EditText)findViewById(R.id.et_name);
        npassword= (EditText)findViewById(R.id.et_password);

        bLogin.setOnClickListener(this);
        bRegister.setOnClickListener(this);
        dbManager = new DBManager(this);
    }
    private void initSpinner() {
        Resources res =getResources();
        String[] type=res.getStringArray(R.array.user_type);//将province中内容添加到数组city中
        final Spinner mSpinner = (Spinner)findViewById(R.id.spinner2);
        //为下拉列表定义一个适配器
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, type);
        //添加数据
        mSpinner.setAdapter(adapter);
        //点击响应事件
        mSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View view, int arg1, long arg2) {
                userType= mSpinner.getItemAtPosition(arg1).toString();
                System.out.println(adapter.getItem(arg1));  //输出所选项目
                Toast.makeText(RegisteOrLogin.this,userType,Toast.LENGTH_SHORT).show();
            }
            public void onNothingSelected(AdapterView<?> arg0) {
                String text = "请选择用户类型";
                Toast toast = Toast.makeText(RegisteOrLogin.this, text, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.LEFT,0, 0);
                toast.show();
            }
        });
    }
    private void saveCurrentData(String loginName,int type){
        sharedPreferences = getSharedPreferences("userinfo",MODE_PRIVATE);
        editor = sharedPreferences.edit();
        editor.putString("name",loginName);
        editor.putInt("type",type);
        editor.commit();
    }
    private void register(String type,String username,String password){
        Log.d("Reminder","正在注册");
        if(type.equals("普通用户")){
            if(!dbManager.checkAlreadyUser(username)){
                User user = new User(username,password,1);
                dbManager.addUser(user);
                System.out.println("注册成功");
            }else Toast.makeText(RegisteOrLogin.this,"用户名已存在，换一个吧",Toast.LENGTH_SHORT).show();

        }
        else if(type.equals("商家")){
            if(!dbManager.checkAlreadySeller(username)){
                Seller seller = new Seller();
                //(username,password,2);
                seller.setSellerName(username);
                seller.setPassword(password);
                seller.setType(2);
                dbManager.addSeller(seller);
                Log.d("Reminder","注册成功");
            }else Toast.makeText(RegisteOrLogin.this,"用户名已存在，换一个吧",Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(RegisteOrLogin.this,"您没有此权限",Toast.LENGTH_SHORT).show();
        }
    }
    private void login(String type,String username,String password){
        Log.d("Reminder","正在登陆");
        if(type.equals("普通用户")){
            if(dbManager.checkLoginUser(username,password)){
                Toast.makeText(RegisteOrLogin.this,"登录成功",Toast.LENGTH_SHORT).show();
                saveCurrentData(username,1);
                this.finish();
            }
            else Toast.makeText(RegisteOrLogin.this,"用户名或密码错误,请重试",Toast.LENGTH_SHORT).show();
        }
        else if(type.equals("商家")){
            if(dbManager.checkLoginSeller(username,password)){
                Toast.makeText(RegisteOrLogin.this,"商家登录成功",Toast.LENGTH_SHORT).show();
                saveCurrentData(username,2);
                this.finish();
            }
            else Toast.makeText(RegisteOrLogin.this,"用户名或密码错误,请重试",Toast.LENGTH_SHORT).show();
        }
        else{
            if(username.equals("admin") && password.equals(MD5Util.md5("123456"))){
                System.out.println("已经进入管理员界面");
                saveCurrentData("admin",3);
                this.finish();
            }
            else Toast.makeText(RegisteOrLogin.this,"用户名或密码错误,请重试",Toast.LENGTH_SHORT).show();
        }
    }

}
